import { chunkArray, sendMessage } from "../../utils";
import type ConcurrentExecutor from "../../class/ConcurrentExecutor";

// 找到popover的确定按钮,用来处理二次删除确认
export function findConfirmButton(): Promise<HTMLButtonElement> {
  return new Promise((resolve, reject) => {
    const maxTime = 1000; // 最大等待时间1秒
    const interval = 200; // 检查间隔200ms
    let elapsedTime = 0;

    const checkButton = () => {
      const confirmSection = document.querySelector(
        ".so-popover .so-popover-content .so-popover-confirm .so-popover-footer"
      );
      if (confirmSection) {
        const buttons = confirmSection.querySelectorAll("button");
        const length = buttons.length;
        if (length) {
          resolve(buttons[length - 1]);
        }
        return;
      }

      elapsedTime += interval;

      if (elapsedTime >= maxTime) {
        reject("未找到确定按钮");
      } else {
        setTimeout(checkButton, interval);
      }
    };

    checkButton();
  });
}

// 删除商品
export function deleteSkc(currentSkuDelete: HTMLButtonElement) {
  return new Promise((resolve, reject) => {
    if (!document.contains(currentSkuDelete)) {
      resolve(true);
      return;
    }
    currentSkuDelete.click();
    findConfirmButton()
      .then((deleteConfirmButton: HTMLButtonElement) => {
        deleteConfirmButton?.click();
        resolve(true);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// 根据价格文案返回价格和币种, 如: 100 USD 和 特价: 100 USD
export function parsePrice(text: string) {
  const priceMatch = text.match(/(\d+(?:,\d{3})*(?:\.\d+)?)\s*([A-Za-z$€£¥]+)/);

  if (!priceMatch) {
    return {
      price: null,
      currency: null,
    };
  }

  const [, priceValue, currencyValue] = priceMatch;

  return {
    price: priceValue,
    currency: currencyValue,
  };
}

// 根据操作TD找到删除按钮
export function findDeleteButton(operateTdElement: Element) {
  const buttons = operateTdElement.querySelectorAll("button");
  const length = buttons.length;
  if (length === 1) {
    return buttons[0];
  }
  return Array.from(buttons).find((button) => {
    return (
      button.textContent &&
      ["删除", "删除商品", "剔除商品", "Delete", "Remove"].includes(
        button.textContent.trim()
      )
    );
  });
}

// 传入skuCode获取ERP货源价格
export async function getErpSkuPriceMap({
  skuCodeList,
  shopId,
  platform,
  baoyiplus_accessToken,
}: {
  skuCodeList: string[];
  shopId: string;
  platform: string;
  baoyiplus_accessToken: string;
}) {
  const promiseArray: any[] = [];
  const chunkSkuCodeList = chunkArray(skuCodeList, 50);
  chunkSkuCodeList.forEach((skuCodeChunk) => {
    promiseArray.push(
      sendMessage({
        type: "getSkuPrice",
        data: {
          outId: `#in#${skuCodeChunk.join(",")}`,
          shopId,
        },
        platform,
        token: baoyiplus_accessToken,
      })
    );
  });

  return Promise.all(promiseArray).then((resList: any) => {
    const erpCodeInfoMap = resList.reduce((obj: any, res: any) => {
      (res?.data || []).forEach((record: any) => {
        const { outId, sourcePrice, sourceCurrency } = record;
        obj[outId] = {
          sourcePrice,
          sourceCurrency,
        };
      });
      return obj;
    }, {});
    return erpCodeInfoMap;
  });
}

export async function getGoodsListData({
  data,
  startPageNum = 1,
  getPayloadData,
  getGoodsList,
  filterGoodsDataByErpPriceMap,
  concurrentExecutor,
}: {
  data: any;
  startPageNum: number;
  getPayloadData: () => Promise<any>;
  getGoodsList: (params: any) => Promise<any>;
  filterGoodsDataByErpPriceMap: (args: {
    enableGoodsData: any[];
    shopId: string;
    platform: string;
    baoyiplus_accessToken: string;
    multiplierMinInput: number;
    multiplierMaxInput: number;
    isOnlyAddGoods: boolean;
  }) => Promise<any[]>;
  concurrentExecutor: ConcurrentExecutor;
}) {
  const {
    shopId,
    platform,
    baoyiplus_accessToken,
    multiplierMinInput,
    multiplierMaxInput,
    addGoodsNumber,
    isOnlyAddGoods = false,
  } = data;
  const uploadNumber = Number(addGoodsNumber) || 500;

  const payloadData = await getPayloadData();
  const page_size = 500;
  const goodsList: any[] = [];
  let totalPage = 0;
  let shouldStop = false;

  // 首先获取第一页来确定总页数
  const firstPageData = await getGoodsList({
    ...payloadData,
    page_num: startPageNum,
    page_size,
  });

  if (firstPageData?.info?.meta?.count) {
    const total = Number(firstPageData.info.meta.count);
    totalPage = Math.ceil(total / page_size);

    // 处理第一页数据
    const firstPageGoods = (firstPageData?.info?.data || []) as any[];
    const enableGoodsData = firstPageGoods.filter((goods) => {
      return !goods?.error_code;
    });
    if (enableGoodsData.length) {
      const filteredGoodsData = await filterGoodsDataByErpPriceMap({
        enableGoodsData,
        shopId,
        platform,
        baoyiplus_accessToken,
        multiplierMinInput,
        multiplierMaxInput,
        isOnlyAddGoods,
      });
      goodsList.push(...filteredGoodsData);
    }
  }

  // 如果已经获取到足够的数据，直接返回
  if (goodsList.length >= uploadNumber) {
    shouldStop = true;
  }

  if (!shouldStop && totalPage > 1) {
    // 创建并发执行器

    // 创建任务数组，从第2页开始
    const tasks = [];
    for (let page_num = startPageNum + 1; page_num <= totalPage; page_num++) {
      tasks.push(async () => {
        if (shouldStop) return;

        const resData = await getGoodsList({
          ...payloadData,
          page_num,
          page_size,
        });

        const goodsDataList = (resData?.info?.data || []) as any[];
        const enableGoodsData = goodsDataList.filter((goods) => {
          return !goods?.error_code;
        });

        // 直接添加所有有效数据，不在这里限制数量
        if (enableGoodsData.length) {
          const filteredGoodsData = await filterGoodsDataByErpPriceMap({
            enableGoodsData,
            shopId,
            platform,
            baoyiplus_accessToken,
            multiplierMinInput,
            multiplierMaxInput,
            isOnlyAddGoods,
          });
          goodsList.push(...filteredGoodsData);
        }

        // 检查是否达到目标数量
        if (goodsList.length >= uploadNumber) {
          shouldStop = true;
        }
      });
    }

    // 并发执行所有任务
    await concurrentExecutor.execute(tasks);
  }

  // 最后统一处理数量限制
  const finalGoodsList = goodsList.slice(0, uploadNumber);
  return finalGoodsList;
}

// 创建成功提示通用方法
export function showCustomDialog({
  message,
  buttons,
}: {
  message: string;
  buttons: { label: string; onClick: () => void }[];
}) {
  // 移除旧的弹窗
  const old = document.getElementById("__baoyi_custom_tip_dialog__");
  if (old) {
    old.remove();
  }

  const dialog = document.createElement("div");
  dialog.id = "__baoyi_custom_tip_dialog__";
  dialog.style.position = "fixed";
  dialog.style.top = "0";
  dialog.style.left = "0";
  dialog.style.width = "100vw";
  dialog.style.height = "100vh";
  dialog.style.background = "rgba(0, 0, 0, 0.35)";
  dialog.style.display = "flex";
  dialog.style.alignItems = "center";
  dialog.style.justifyContent = "center";
  dialog.style.zIndex = "9999";

  const modal = document.createElement("div");
  modal.style.background = "#fff";
  modal.style.borderRadius = "12px";
  modal.style.padding = "32px 24px";
  modal.style.boxShadow = "0 2px 16px rgba(0,0,0,0.1)";
  modal.style.textAlign = "center";
  modal.style.minWidth = "300px";
  modal.style.maxWidth = "90vw";

  const msg = document.createElement("div");
  msg.innerText = message;
  msg.style.fontSize = "22px";
  msg.style.fontWeight = "bold";
  msg.style.marginBottom = "24px";

  const btnContainer = document.createElement("div");
  btnContainer.style.display = "flex";
  btnContainer.style.justifyContent = "center";
  btnContainer.style.gap = "16px";

  buttons.forEach(({ label, onClick }) => {
    const btn = document.createElement("button");
    btn.innerText = label;
    btn.style.padding = "10px 24px";
    btn.style.border = label === "前往查看" ? "none" : "1px solid #704fff";
    btn.style.borderRadius = "6px";
    btn.style.background = label === "前往查看" ? "#704fff" : "#fff";
    btn.style.color = label === "前往查看" ? "#fff" : "#704fff";
    btn.style.fontSize = "16px";
    btn.style.cursor = "pointer";
    btn.onclick = () => {
      dialog.remove();
      onClick();
    };
    btnContainer.appendChild(btn);
  });

  modal.appendChild(msg);
  modal.appendChild(btnContainer);
  dialog.appendChild(modal);
  document.body.appendChild(dialog);
}